import { getLoginCheck, deleteUserData } from "@/api"

export default {
  namespaced: true,
  state: {
    user: {
      username: localStorage.getItem("username"),
      token: localStorage.getItem("token"),
    },
  },
  getters: {},
  actions: {
    async userLogin({ commit }, user) {
      const result = await getLoginCheck(user)
      if (result.code === 200) {
        commit("USER_LOGIN", result.data)
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async userOut({ commit }) {
      const result = await deleteUserData()
      if (result.code === 200) {
        commit("USE_ROUT")
      } else {
        console.log(result.message)
      }
    },
  },
  mutations: {
    USER_LOGIN(state, data) {
      state.user.username = data.name
      state.user.token = data.token

      localStorage.setItem("username", data.name)
      localStorage.setItem("token", data.token)
    },
    USE_ROUT(state) {
      state.user.username = ""
      state.user.token = ""
      localStorage.removeItem("username")
      localStorage.removeItem("token")
    },
  },
}
